<template>
  <div class="app-container">
    <!-- 查询行 -->
    <el-row :gutter="10" class="mb8 query-row">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="88px" >
        <el-form-item label="中间库配置" prop="zjkconfig">
          <el-select v-model="queryParams.zjkConfig" placeholder="请选择中间库" clearable size="mini" filterable @change="handleZJKChange" style="width: 300px" >
            <el-option v-for="item in zjkOptions" :key="item.value" :label="item.label" :value="item.value" >
              <span style="float: left">{{ item.label }}</span>
              <span style="float: right; color: lightblue; font-size: 13px">{{ item.code }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="查询条件" prop="path">
          <el-input v-model="queryParams.path" placeholder="双击表格自动带入条件" clearable size="mini" style="width: 380px" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" >搜索</el-button >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery" >重置</el-button >
        </el-form-item>
      </el-form>
    </el-row>
    <!-- 按钮行 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-tooltip content="按照查询条件导出excel,和选中无关" placement="top-start" effect="dark" >
          <el-button type="primary" plain icon="el-icon-download" size="mini" :loading="loading" @click="handleExport" >导出</el-button >
        </el-tooltip>
      </el-col>

      <!-- <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport">导入更新</el-button>
      </el-col> -->

      <el-col :span="1.5">
        <el-tooltip content="将选中数据进行手工同步,需要在流程配置中启用流程" placement="top-start" effect="dark" >
          <el-button type="info" plain size="mini" :loading="loading" @click="handleFlow" :disabled="!currentRow" >
            手工同步
          </el-button>
        </el-tooltip>
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :loading="loading" @click="handleSQLInfo" >SQL配置</el-button >
      </el-col>

      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :loading="loading" @click="handleDBInfo" >链接配置</el-button >
      </el-col>

      <el-col :span="1.5">
        <el-tooltip content="清除日志中的所有错误数据" placement="top-start" effect="dark">
        <el-button type="info" plain icon="el-icon-delete" size="mini" :loading="loading" @click="handleErrorClear" >
          清除错误数据
        </el-button>
        </el-tooltip>
      </el-col>

      <!-- 定时刷新 -->
      <el-col :span="1.5">
        <el-input-number v-model="timeSec" :min="5" :max="600" label="秒" size="mini" :disabled="timeChecked" ></el-input-number>
      </el-col>
      <el-col :span="1.5">
        <el-checkbox v-model="timeChecked" label="定时刷新(秒)" size="mini" border @change="handleTimeChecked" ></el-checkbox>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table ref="mainTable" v-loading="loading" :data="zjklist" @cell-dblclick="handleCellDBClick" :row-style="{ height: '32px' }"
      @selection-change="handleSelectionChange" @current-change="handleCurrentChange" :cell-style="{ padding: '0px' }"
      highlight-current-row border :height="tableHeight" >
      <!-- 取消多选框 -->
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <el-table-column v-for="item in columns" :key="item" :label="item" :width="computeWidth(zjklist, item)"
        align="center" :prop="item" show-overflow-tooltip sortable />
    </el-table>

    <!-- 分页控件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 查看流程配置,通过属性传入参数 -->
    <flow-info-dlg :visible.sync="sqlOpen" :code="sqlConf"></flow-info-dlg>
    <!-- 运行信息 -->
    <RunTimeDlg ref="RunTimeDlg"></RunTimeDlg>
    <!-- 导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open"
      width="400px" append-to-body >
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="uploadUrl()"
        :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
        :auto-upload="false" drag >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <!-- <div class="el-upload__tip" slot="tip">
          <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
          <el-link type="info" style="font-size: 12px" @click="importTemplate">下载模板</el-link>
        </div> -->
        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
        <div class="el-upload__tip" style="color: darkred" slot="tip">
          Excel字段说明: 需要更新的物理表字段名!
          必须包含"中间库配置"中的"更新主键"
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listzjk, listzjkConfig, exportzjk, handleflow, } from "@/api/aitcommon/aitzjk";
import { computeColWidth } from "@/utils/ait";
import FlowInfoDlg from "@/components/AIT/FlowInfo";
import { getToken } from "@/utils/auth";
import RunTimeDlg from "@/components/AIT/RunTimeDlg";
import { errorClear } from "@/api/aitcommon/EntityInfo";

export default {
  name: "aitzjk",
  components: { FlowInfoDlg, RunTimeDlg },
  data() {
    return {
      //SQL配置界面
      sqlOpen: false,
      sqlConf: "",
      //表格高度
      tableHeight: 500,
      // 定时刷新
      timeSec: 60,
      timeChecked: false,
      timer: {},
      //zjk配置,select控件绑定
      zjkOptions: [],
      //zjk配置列表及当前行
      zjkConfigList: [],
      zjkConfigCurr: null,
      // 显示字段
      columns: [],
      // 遮罩层
      loading: true,
      // 选中数组
      selectedRows: [],
      // 当前行
      currentRow: null,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 测试节点1表格数据
      zjklist: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        sql: "",
        db: "",
        path: "",
        zjkConfig: "",
        zjkName: "",
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/ait/common/sql/excelUpdate",
      },
    };
  },
  created() {
    this.getzjkConfig();
    this.getList();
  },
  mounted() {
    this.$nextTick(() => {
      // window窗口大小变化后,页面table自适应高度,需要点击 刷新
      // window.innerHeight 浏览器窗口的可见高度，下面的 220 是除了table最大高度的剩余空间。
      let height =
        window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 220;
      this.tableHeight = height;
    });
  },
  methods: {
    //清除所有错误数据
    handleErrorClear() {
      this.$confirm("将清除日志中所有错误数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.loading = true;
        errorClear().then((res) => {
            this.getList();
            this.msgSuccess("错误数据清除完成!");
          }).finally((res) => {
            this.loading = false;
          });
      });
    },
    handleSQLInfo() {
      if (this.zjkConfigCurr) {
        this.sqlConf = this.zjkConfigCurr && this.zjkConfigCurr.sqlConf;
        this.sqlOpen = true;
      }
    },
    handleDBInfo() {
      if (this.zjkConfigCurr) {
        this.sqlConf = this.zjkConfigCurr && this.zjkConfigCurr.dbConf;
        this.sqlOpen = true;
      }
    },
    // 表格宽度自适应
    computeWidth(datalist, col) {
      return computeColWidth(datalist, col);
    },
    // 中间库选择变化
    handleZJKChange(val) {
      if (val) {
        //从中间库配置列表中获取当前配置
        let list = this.zjkConfigList.filter((item) => {
          return item.id === val;
        });
        this.zjkConfigCurr = list[0];
      } else {
        //console.info('handleZJKChange', val)
        this.zjkConfigCurr = null;
      }
      // this.queryParams.path = '';
      // this.zjklist = null;
      // this.columns = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // console.info('handleSelectionChange',selection)
      // this.ids = selection.map((item) => item.id);
      this.selectedRows = selection;
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleCurrentChange(val) {
      // console.info('handleCurrentChange',val)
      this.currentRow = val;
      if (val) {
        this.$refs.mainTable.toggleRowSelection(val);
      }
    },
    handleTimeChecked(check) {
      // console.info('handleTimeChecked',check);
      if (check) {
        this.timer = window.setInterval(this.handleQuery, this.timeSec * 1000);
      } else {
        window.clearInterval(this.timer);
      }
    },
    handleCellDBClick(row, col, cel, event) {
      if (this.queryParams.path) {
        this.queryParams.path +=
          " and " + col.label + "='" + row[col.label] + "'";
      } else {
        this.queryParams.path = col.label + "='" + row[col.label] + "'";
      }
    },

    /**
     * 手工同步
     * 将选择数据进行手工同步
     * 需要在中间库配置中启用流程
     * 执行后,弹窗 运行信息
     */
    handleFlow() {
      if (!this.currentRow) {
        this.msgError("请先选择行");
        return;
      }
      if (!this.zjkConfigCurr) {
        this.msgError("请选择中间库配置");
        return;
      }
      if (!this.selectedRows.length) {
        this.msgError("请先选择数据");
        return;
      }
      if (!this.zjkConfigCurr.enableFlow) {
        this.msgError("该配置未[启用流程]");
        return;
      }
      if (!this.zjkConfigCurr.flowType || !this.zjkConfigCurr.codeField) {
        this.msgError("该中间库未配置[流程类型]或[编码字段]");
        return;
      }

      this.loading = true;
      // 如果this.zjkConfigCurr.flowType配置格式${XXX},需要从焦点数据中获取flowCode
      // 否则this.zjkConfigCurr.flowType就是flowCode
      let matchReg = this.zjkConfigCurr.flowType.match(/\$\{(.*)\}/);
      let flowCode = "";
      if (matchReg) {
        flowCode = this.currentRow[matchReg[1]];
      } else {
        flowCode = this.zjkConfigCurr.flowType;
      }
      // let codes = this.selectedRows.map(item => item[this.zjkConfigCurr.codeField])
      // 从选中行改为焦点行
      let code = this.currentRow[this.zjkConfigCurr.codeField];
      handleflow(flowCode, [code])
        .then((response) => {
          //弹出 运行信息 窗框
          this.$refs.RunTimeDlg.openDlg(flowCode, this.getList);
        })
        .finally((res) => {
          this.loading = false;
        });
    },

    /* 查询中间库配置 */
    getzjkConfig() {
      this.loading = true;
      listzjkConfig().then((response) => {
        this.zjkConfigList = response.rows;
        this.zjkOptions = [];
        if (this.zjkConfigList) {
          this.zjkConfigList.forEach((item) => {
            this.zjkOptions.push({
              value: item.id,
              label: item.name,
              code: item.code,
            });
          });
        }
        this.loading = false;
      });
    },
    /** 查询列表 */
    getList() {
      if (this.zjkConfigCurr) {
        this.queryParams.sql = this.zjkConfigCurr.sqlConf;
        this.queryParams.db = this.zjkConfigCurr.dbConf;
        this.queryParams.zjkName = this.zjkConfigCurr.name;
      } else {
        // this.msgError("请选择中间库配置");
        this.zjklist = null;
        this.total = 0;
        return;
      }

      this.loading = true;
      listzjk(this.queryParams)
        .then((response) => {
          if (response.data) {
            this.zjklist = response.data.rows;
            this.total = response.data.total;
          } else {
            this.zjklist = null;
            this.total = 0;
          }

          // 重置列名
          this.columns = [];
          if (this.zjklist) {
            let rec = this.zjklist[0];
            for (var key in rec) {
              this.columns.push(key);
            }
          }

          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      if (!this.zjkConfigCurr) {
        this.msgInfo("请选择中间库配置");
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },

    /**
     * 导出按钮操作
     * 按照查询条件导出,和选择框无关
     */
    handleExport() {
      if (this.zjkConfigCurr) {
        this.queryParams.sql = this.zjkConfigCurr.sqlConf;
        this.queryParams.db = this.zjkConfigCurr.dbConf;
        this.queryParams.zjkName = this.zjkConfigCurr.name;
      } else {
        this.msgError("请先选择中间库配置");
        return;
      }

      this.$confirm("是否确认导出数据?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.loading = true;
          return exportzjk(this.queryParams);
        })
        .then((response) => {
          this.download(response.msg);
          this.loading = false;
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /** 导入按钮操作 */
    handleImport() {
      if (!this.zjkConfigCurr) {
        this.msgError("请先选择中间库配置");
        return;
      }
      if (!this.zjkConfigCurr.enableUpdate) {
        this.msgError("该配置未[启用更新]");
        return;
      }
      if (!this.zjkConfigCurr.updateTable || !this.zjkConfigCurr.updateKey) {
        this.msgError("该中间库未配置[更新表名]或[更新主键]");
        return;
      }

      this.upload.title = "导入更新";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    // 获取上传动作url
    uploadUrl() {
      if (this.zjkConfigCurr)
        return (
          this.upload.url +
          "?db=" +
          this.zjkConfigCurr.dbConf +
          "&table=" +
          this.zjkConfigCurr.updateTable +
          " &key=" +
          this.zjkConfigCurr.updateKey
        );
      else return "";
    },
  },
};
</script>
